import Taro from "@tarojs/taro";
import { useEffect } from "react";
import { Text, View } from "@tarojs/components";

import ByText from "@/components/ui/ByText";
import ByCell from "@/components/ui/ByCell";
import Moment from "@/components/app/Moment";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import Uploader from "@/components/app/Uploader";
import ByCounter from "@/components/ui/ByCounter";
import FormInput from "@/components/common/FormInput";
import ByImageGroup from "@/components/ui/ByImageGroup";
import ByPopupBottom, {
  ByPopupBottomEvent,
} from "@/components/ui/ByPopupBottom";

import ApiCrm from "@/api/crm";
import useForm from "@/hooks/useForm";
import useGetHolidayList from "@/hooks/useGetHolidayList";
import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";

import { getPeriodEndDate } from "@/utils";

import type { ConstructionPlanDetail } from "@/types/construction";

type PopupExtensionProps = {
  intentCustomerId: number
  isSkipHoliday?: boolean;
  source: ConstructionPlanDetail;

  onSuccess: () => void;
};

/**
 *
 * 延期表单提交数据
 */
export interface FormModel {
  /**
   * 施工ID
   */
  constructionId?: number;
  /**
   * 施工计划ID
   */
  constructionPlanId: number;
  /**
   * 施工项目名称
   */
  constructionProjectName?: string;
  /**
   * 延期类别
   */
  extensionCatagory: number;
  /**
   * 延期天数
   */
  extensionDate: number;
  /**
   * 延期原因
   */
  extensionReason?: string;
  /**
   * 延期类型
   */
  extensionType?: string;
  /**
   * 是否订单延期
   */
  isOrderExtension: boolean;
  /**
   * 图片列表
   */
  picList: string[];
  /**
   * 计划完成日期
   */
  planFinishDate: string;
  /**
   * 计划完成编辑日期
   */
  planFinishEditDate: string;
  /**
   * 计划开始日期
   */
  planStartDate: string;
  /**
   * 计划开始编辑日期
   */
  planStartEditDate: string;
  /**
   * 备注
   */
  remark?: string;
  /**
   * 未知？
   */
  workFlowDefineId?: number;
}

const extensionTypeList = ["客户原因", "公司原因"];

const rules = {
  extensionDate: [
    {
      type: 'number',
      validator: (_, value, callback) => {
        if (!value || value <= 0) {
          callback(new Error('延期时长必须大于0'));
        } else {
          callback();
        }
      }
    }
  ],
  extensionType: { required: true, message: "请选择延期原因" },
  // extensionCatagory: { required: true, message: "请选择是否顺延" },
};

export default ({
  source,
  intentCustomerId,
  isSkipHoliday = false,

  onCancel,
  onSuccess,
}: PopupExtensionProps & ByPopupBottomEvent) => {
  // 获取假期列表
  const [holidayList] = useGetHolidayList();

  // 查询并并绑定审批流
  const [workflowList, { loading: bindLoading, bind }] = useWorkflowDefinition(
    { typeCode: "Forms_FormConstructionPlanExtension" },
    {
      onSuccess() {
        Taro.showToast({ title: "操作成功" });
        onSuccess();
      },
    }
  );

  // 提交表单
  const { loading, model, setModel, submit } = useForm<FormModel>(
    ApiCrm.delayConstruction,
    {
      //@ts-expect-error
      rules,
      defaultModel: {
        picList: [],
        isOrderExtension: true,
        planStartDate: source.planStartDate,
        planFinishDate: source.planFinishDate,
        planStartEditDate: source.planStartEditDate,
        planFinishEditDate: source.planFinishEditDate,
        constructionPlanId: source.constructionPlanId,
      },
      onSuccess(res) {
        // onSuccess();
        bind({
          intentCustomerId,
          businessId: res.extensionFormId + ""
        });
      },
    }
  );

  useEffect(() => {
    // startState: 0 待开工 1 待完工
    const {
      startState,
      planStartDate,
      planFinishDate,
      planStartEditDate,
      planFinishEditDate,
    } = source;
    const { extensionDate, isOrderExtension } = model;

    // 如果开启顺延，重新结算时间
    if (extensionDate && extensionDate > 0) {
      // 1. 开工：重新计算开工时间和结束时间 PlanStartEditDate 和 PlanFinishEditDate
      model.planStartEditDate =
        isOrderExtension && startState == 0
          ? getPeriodEndDate(
            planStartDate,
            extensionDate + 1,
            holidayList,
            isSkipHoliday
          ).format("YYYY-MM-DD")
          : planStartEditDate || planStartDate;

      // 2. 完工：重新计算完工时间 PlanFinishEditDate
      model.planFinishEditDate = isOrderExtension
        ? getPeriodEndDate(
          planFinishEditDate || planFinishDate,
          extensionDate + 1,
          holidayList,
          isSkipHoliday
        ).format("YYYY-MM-DD")
        : planFinishEditDate || planFinishDate;

      setModel(model);
    }
  }, [model.extensionDate, model.isOrderExtension]);

  return (
    <ByPopupBottom title="延期" onCancel={onCancel}>
      <View className="max-h-[70vh] px-4 overflow-y-auto">
        <ByCell vertical label="计划时间">
          <View>
            <Moment value={source.planStartDate} />
            <Text className="px-3">~</Text>
            <Moment value={source.planFinishDate} />
          </View>
        </ByCell>

        <ByCell
          requierd
          vertical
          label="计划时间"
          tip={model.planFinishEditDate && `延期至${model.planFinishEditDate}`}
        >
          <ByCounter
            min={0}
            initialValue={model.extensionDate}
            onChange={(e) => setModel({ extensionDate: e })}
          />
          <ByText size="sm" type="third">
            天
          </ByText>
        </ByCell>

        <ByCell vertical label="延期原因">
          <BySpace>
            {extensionTypeList.map((item, index) => (
              <ByButton
                type={model.extensionType === item ? "primary" : "info"}
                variant={model.extensionType === item ? "solid" : "outline"}
                onClick={() =>
                  setModel({
                    extensionType: item,
                    extensionCatagory: index,
                    // 客户原因必须顺延
                    isOrderExtension:
                      index == 0 ? true : model.isOrderExtension,
                  })
                }
              >
                {item}
              </ByButton>
            ))}
          </BySpace>
        </ByCell>

        <ByCell vertical label="是否顺延">
          <BySpace>
            <ByButton
              type={model.isOrderExtension ? "primary" : "info"}
              variant={model.isOrderExtension ? "filled" : "outline"}
              onClick={() => setModel({ isOrderExtension: true })}
            >
              是
            </ByButton>
            <ByButton
              type={
                model.extensionCatagory !== 0 && !model.isOrderExtension
                  ? "primary"
                  : "info"
              }
              variant={!model.isOrderExtension ? "filled" : "outline"}
              onClick={() =>
                model.extensionCatagory !== 0 &&
                setModel({ isOrderExtension: false })
              }
            >
              否
            </ByButton>
          </BySpace>
        </ByCell>

        <ByCell vertical label="延期备注">
          <FormInput
            type="textarea"
            placeholder="请输入..."
            value={model.extensionReason}
            onChange={(e) => setModel({ extensionReason: e })}
          />
        </ByCell>

        <ByCell vertical label="延期照片">
          <ByImageGroup
            showDelete
            urls={model.picList}
            onChange={(res) => setModel({ picList: res })}
            slotFooter={
              <Uploader
                onSuccess={(e) =>
                  setModel({ picList: model.picList.concat(e) })
                }
              />
            }
          />
        </ByCell>

        <ByButton
          size="large"
          loading={loading || bindLoading}
          className="mt-6 mb-3 w-2/3"
          onClick={() => submit()}
        >
          提交
        </ByButton>
      </View>
    </ByPopupBottom>
  );
};
